# encoding=utf-8
import logging
import os
import time
from datetime import datetime

from SerialRecv import SerialRecv
from SerialSend import SerialSend

# logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')


class SerialHost(SerialSend, SerialRecv):
    def __init__(self,
                 device: str,
                 rate: int = 115200,
                 package_size: int = 64,
                 tmp_dir: str = "tmp-data-host"):
        super().__init__(device, rate, package_size)
        # 环境信息
        self.tmp_dir = tmp_dir
        os.makedirs(self.tmp_dir, exist_ok=True)

        # 主: 模块启动 -> 清空所有串口缓存
        self._make_sure_flush()

    def send_command(self, number: int):
        self._make_sure_flush()

        # 主: OUT 1B, 告诉从机执行哪种算法
        command_array = bytearray()
        command_array.append(self.OUT)
        command_array.append(number)
        command_bytes = bytes(command_array)

        # send
        if not self._send_raw_data(command_bytes):
            return False

        # recv
        try:
            # 没有及时返回数据，可能死机
            return bytearray(self._read_raw_data(1))[0] == self.ACK
        except Exception as e:
            return False

    def send_to_device(self, file_path: str):
        self._make_sure_flush()

        return self.send_raw_file(file_path)

    def query_device_status(self, number: int):
        self._make_sure_flush()

        # 主: QUERY 1B, 查询状态
        command_array = bytearray()
        command_array.append(self.QUERY)
        command_array.append(number)
        command_bytes = bytes(command_array)

        # send
        if not self._send_raw_data(command_bytes):
            return self.QUERY_ERROR

        # recv
        try:
            return bytearray(self._read_raw_data(1))[0]
        except Exception as e:
            return self.QUERY_ERROR


    def get_device_data(self, number: int, file_suffix: str='.jpg'):
        self._make_sure_flush()

        # 主: QUERY 1B, 查询状态
        command_array = bytearray()
        command_array.append(self.IN)
        command_array.append(number)
        command_bytes = bytes(command_array)

        # send
        if not self._send_raw_data(command_bytes):
            return ""

        # recv
        recv_file = self._gen_file_name(file_suffix)
        if not self.recv_raw_file(recv_file):
            return ""
        else:
            return recv_file


    def _gen_file_name(self, suffix: str = ".jpg"):
        time_name = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        return os.path.join(self.tmp_dir, time_name + suffix)


if __name__ == '__main__':
    # 3. 主: 模块启动 -> 清空所有串口缓存
    serial_host = SerialHost("/dev/ttyACM0", 6000000, 256)

    # 4. 主: OUT 1B, 告诉从机执行哪种算法
    code = 1
    result = serial_host.send_command(code)
    if not result:
        print("指令发送失败")
        exit(-1)

    # 7. 主: send_raw_file
    result = serial_host.send_to_device("sample-data/sample-image.jpg")
    if not result:
        print("文件发送失败")
        exit(-1)

    # 9. 主: IN 1B, 获取从机执行算法结果,
    # 10. 主: 进入原始数据等待模式, recv_raw_file
    for i in range(3):
        result = serial_host.query_device_status(code)
        print("Now Result is: ", result)

        if result == serial_host.QUERY_DONE:
            if code == 1:
                recv_file = serial_host.get_device_data(code, '.jpg')
            else:
                recv_file = serial_host.get_device_data(code, '.txt')
            print("接收到的文件是", recv_file)
            break

        time.sleep(1)




